package db

import (
	"errors"

	"github.com/astaxie/beego/orm"
    _ "github.com/lib/pq"
    "github.com/kotocean/cricket/auth/db/models"
)

func init() {
	// PostgreSQL 配置
    orm.RegisterDriver("postgres", orm.DRPostgres) // 注册驱动
    orm.RegisterDataBase("default", "postgres", "user=my_user password=password123 dbname=cricket_db host=127.0.0.1 port=5432 sslmode=disable")
}

func GetPersonInfo(name string) (*models.Person, error) {
	o := orm.NewOrm()
	o.Using("default")

	// 查询用户
    person := models.Person{Name: name}

    err := o.Read(&person, "Name")
    if err == orm.ErrNoRows {
	    return nil, errors.New("查询不到")
	} else if err == orm.ErrMissPK {
	    return nil, errors.New("找不到主键")
	} else {
	    return &person, nil
	}
}
func GetClientInfo(clientId string) (*models.Client, error) {
	o := orm.NewOrm()
	o.Using("default")

	// 查询用户
    client := models.Client{ClientId: clientId}

    err := o.Read(&client, "ClientId")
    if err == orm.ErrNoRows {
	    return nil, errors.New("查询不到")
	} else if err == orm.ErrMissPK {
	    return nil, errors.New("找不到主键")
	} else {
	    return &client, nil
	}
}

func SaveRecord(record models.Record) (*models.Record, error) {
	o := orm.NewOrm()
	o.Using("default")

	id, err := o.Insert(&record)
	if err == nil {
	    record.Id = id
	    return &record, nil
	}else{
		return nil, errors.New("保存到数据库失败")
	}
}

func GetRecord(clientMark string) (*models.Record, error) {
	o := orm.NewOrm()
	o.Using("default")

	record := models.Record{ClientMark: clientMark}

    err := o.Read(&record, "ClientMark")
    if err == orm.ErrNoRows {
	    return nil, errors.New("查询不到")
	} else if err == orm.ErrMissPK {
	    return nil, errors.New("找不到主键")
	} else {
	    return &record, nil
	}
}

func InvalidateToken(clientMark string) (*models.Record, error) {
	o := orm.NewOrm()
	o.Using("default")

	record := models.Record{ClientMark: clientMark}
	if o.Read(&record, "clientMark") == nil {
	    record.Valid = false
	    if _, err := o.Update(&record, "Valid"); err == nil {
	        return &record, nil
	    }else{
	    	return nil, errors.New("更新失败")
	    }
	}else{
		return nil, errors.New("查询不到record")
	}
}

func DeleteRecord(id int64) error {
	o := orm.NewOrm()
	o.Using("default")

	if _, err := o.Delete(&models.Record{Id: id}); err == nil{
		return nil
	}else{
		return err
	}
}
